package com.edu.framework.websocket.handler;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.edu.framework.websocket.WebSocketHolder;
import com.edu.framework.websocket.message.base.Response;
import com.edu.framework.websocket.message.timetable.TimetableRequest;
import com.edu.framework.websocket.message.timetable.TimetableVO;
import com.edu.framework.websocket.service.TimetableService;
import com.edu.system.service.IStudentService;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

@Slf4j
@Component
public class TimetableRequestHandler implements IHandler<TimetableRequest> {

    @Resource
    private TimetableService wsTimetableService;
    @Resource
    private IStudentService iStudentService;

    @Override
    public void execute(WebSocketSession session, TimetableRequest message) {
        if (message == null) {
            return;
        }
        Map<String, String> data = message.getData();
        Long classId = Optional.ofNullable(data.get(TimetableRequest.CLASS_KEY))
            .filter(StrUtil::isNotBlank)
            .map(Long::parseLong)
            .orElseGet(() -> null);
        String cardID = data.get(TimetableRequest.CARD_ID);
        Date lessonDate = Optional.ofNullable(data.get(TimetableRequest.LESSON_DATE_KEY))
            .filter(StrUtil::isNotBlank)
            .map(Long::parseLong)
            .map(a -> new Date(a))
            .orElseGet(Date::new);

        Response<TimetableVO> response = null;
        if (Objects.isNull(classId) && StrUtil.isBlank(cardID)){
            response = Response.fail(TimetableRequest.TYPE, "班级id和卡ID不能同时为空");
        } else {
            TimetableVO vo = wsTimetableService.getTimetable(classId, cardID, lessonDate);
            log.info("查询课表 {} 返回：{}", TimetableRequest.TYPE, JSONObject.toJSONString(vo));
            response = Response.ok(TimetableRequest.TYPE, TimetableRequest.RESP_KEY, vo);
        }

        try {
            WebSocketHolder.send(session,response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String getType() {
        return TimetableRequest.TYPE;
    }
}
